package com.appheader.rongmaphone.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.webkit.WebSettings;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.appheader.rongmaphone.MainActivity;
import com.appheader.rongmaphone.R;
import com.appheader.rongmaphone.cache.file.ResourceFileManager;
import com.appheader.rongmaphone.constants.GlobalVars;
import com.appheader.rongmaphone.service.MusicService;
import com.appheader.rongmaphone.utils.FileUtil;
import com.appheader.rongmaphone.views.AutoNotifyViewPager;
import com.appheader.rongmaphone.views.DragFrameLayout;
import com.appheader.rongmaphone.views.MyWebView;
import com.appheader.rongmaphone.views.VerticalViewPager;
import com.tencent.smtt.export.external.extension.interfaces.IX5WebViewExtension;
import com.tencent.smtt.sdk.WebViewClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

//import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
//import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
//import com.tencent.smtt.sdk.WebSettings;
//import com.tencent.smtt.sdk.WebView;
//import com.tencent.smtt.sdk.WebViewClient;

/**
 * Created by zhep on 2016/9/20.
 * 详情webview浏览页
 */
public class ContentActivity extends FragmentActivity implements View.OnClickListener {
    private static final String TAG = "ContentActivity";
    private PopupWindow mPopupWindow;
    private AutoNotifyViewPager horizontalViewPager;//水平的viewpager
    private VerticalViewPager verticalViewPager;//垂直的viewpager
    private LayoutInflater layoutInflater;
    private LinkedList<View> mViewCache = new LinkedList<>();//建立缓存池，垂直的viewpager
    private List<View> verticalList;
    public static Map<Integer, List<String>> listMap = new HashMap<>();//用于保存二维数据
    private List<String> list;
    private MyHorizontalPagerAdapter myPagerAdapter;
    private RecyclerView image1;
    private RecyclerView image2;
    //悬浮按钮
    private DragFrameLayout frameLayout;
    private RelativeLayout fab;
    private TextView veritcalPageText, vTotalPageText;
    private TextView horizontalPageText, hTotalPageText;
    private TextView currentPage, totalPage;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView recyclerView;
    private View view;
    private String uid;//用户Id
    private String projectId;//方案Id
    private String isOnLine;
    private ImageView backgroundMusic;
    private Animation animation;
    private boolean isPlay = false;
    private Intent intent;
    private String pageType;
    private String weburl;
    private ViewHolder holder;
    private com.tencent.smtt.sdk.WebSettings webSettings;

    private String sdcardRoot;
    private RelativeLayout bottomSelector;
    //滑动控制
    private boolean isScrolling = false;
    private boolean isSmallToBig = true;
    private boolean isBigToSmall = false;
    private int mCurrentPage = 0;
    //记录上一次滑动的positionOffsetPixels值
    private int lastValue = -1;
    private String pageType1;
    private ImageView stopImg;
    boolean isAnimation=true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        this.requestWindowFeature(Window.FEATURE_NO_TITLE);  //去掉标题栏
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //去掉信息栏
        setContentView(R.layout.content_activity);
//        getWindow().setFormat(PixelFormat.TRANSLUCENT);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.
//                SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.
//                SOFT_INPUT_STATE_HIDDEN);
        initPop();
        initView();
        pageType1 = initData();
        if (pageType1.equals("pad")) {
//            int[] location = new int[2];
//            t.getLocationOnScreen(location);
//            int x = location[0];
//            int y = location[1];
            //设置横屏
            //添加全屏的标记
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int winH = metrics.heightPixels;//1
            int winW = metrics.widthPixels;//720
            Log.e(TAG, "onCreate: winH=" + winH + "winW=" + winW);
//            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) frameLayout.getLayoutParams();
//            layoutParams.height = winW;
//            layoutParams.width = winH;
//            frameLayout.setLayoutParams(layoutParams);

//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            bottomSelector.setVisibility(View.GONE);
        } else {
//            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            fab.setVisibility(View.GONE);
        }
        getData();
        animation();

        viewpagerChangeListener();

        backgroundMusic.setOnClickListener(this);
        stopImg.setOnClickListener(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (pageType1.equals("pad")) {
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int winH = metrics.heightPixels;//1
            int winW = metrics.widthPixels;//720
            Log.e(TAG, "onCreate: winH=" + winH + "winW=" + winW);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) frameLayout.getLayoutParams();
            layoutParams.height = winH;
            layoutParams.width = winW;
            frameLayout.setLayoutParams(layoutParams);
        }
    }

    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        switch (requestedOrientation) {
            //横屏
            case (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE):
                break;
            //竖屏
            case (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT):
                break;
        }
        super.setRequestedOrientation(requestedOrientation);
    }

    @Override
    public int getRequestedOrientation() {

        return super.getRequestedOrientation();
    }

    private void getData() {
        verticalList = new ArrayList<>();
        Log.e(TAG, "listMap: " + listMap.size());
        for (int i = 0; i < listMap.size(); i++) {
            View cur = layoutInflater.inflate(R.layout.fragment_web, null);//viewCC.get(position);
            verticalViewPager = (VerticalViewPager) cur.findViewById(R.id.vertical_viewpager);
//            verticalViewPager.setOffscreenPageLimit(2);
            verticalList.add(verticalViewPager);
            verticalViewPager.setAdapter(new MyVerticalPagerAdapter(i, ContentActivity.this));
            verticalPagerChangeListener(verticalViewPager);
        }
        myPagerAdapter = new MyHorizontalPagerAdapter();
        horizontalViewPager.setAdapter(myPagerAdapter);
        horizontalViewPager.setCurrentItem(0);
        verticalViewPager.setCurrentItem(0);
        hTotalPageText.setText("共" + listMap.size() + "页");
        vTotalPageText.setText("共" + listMap.get(0).size() + "页");
        totalPage.setText(listMap.get(0).size() + "");
//      可以设置setOffscreenPageLimit(2)，保持当前页的前两页和后两页。
//        horizontalViewPager.setOffscreenPageLimit(2);//预加载出
    }

    private void verticalPagerChangeListener(final VerticalViewPager verticalViewPager) {
        verticalViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                verticalViewPager.getParent().requestDisallowInterceptTouchEvent(true);
                Log.e(TAG, "vertical-onPageScrolled: position=" + position + "---positionOffset=" + positionOffset + "positionOffsetPixels=" + positionOffsetPixels);
                View verticalView = verticalViewPager.findViewWithTag(verticalViewPager.getCurrentItem());
                if (verticalView != null) {

                    MyWebView myWebView = (MyWebView) verticalView.findViewById(R.id.my_web);

                    if (position == 0) {
                        getAnimation(myWebView);//执行进入动画
//                        myWebView.loadUrl("javascript:slideIntoView()");
                    }
                    if (positionOffsetPixels > 0) {
                        //向右侧滑动
                        Log.e(TAG, "verticalViewPager-onPageSelected: position==" + position + "positionOffsetPixels==" + positionOffsetPixels);
                        myWebView.loadUrl("javascript:slideOutView()");//执行结束动画
                    } else if (positionOffset == 0.0 && positionOffsetPixels == 0) {
                        myWebView.loadUrl("javascript:slideIntoView()");
                        Log.e(TAG, "verticalViewPager-onPageSelected: position==" + position);
                    }
                }
                Log.e(TAG, "onPageScrolled: ===---" + position);
            }

            @Override
            public void onPageSelected(int position) {
                Log.e(TAG, "onPageSelected: ===---" + position);
                horizontalPageText.setText((position + 1) + "");
                currentPage.setText((position + 1) + "");
                Log.e(TAG, "verticalViewPager: " + verticalViewPager.getCurrentItem() + "position=" + position);
//                if (position == 0 || position == 1) {
//                    getAnimation(holder.myWebView);//执行进入动画
//                    holder.myWebView.loadUrl("javascript:slideIntoView()");
//                }
            }

            //            状态改变的时候调用
            @Override
            public void onPageScrollStateChanged(int state) {
//                if (state == 1) {
//                    isScrolling = true;
//                } else if (state == 2) {
//                    isScrolling = false;
//                }
//                getAnimation(holder.myWebView);//执行进入动画
                Log.e(TAG, "onPageScrollStateChanged: ===" + state);
            }
        });
    }


    private void animation() {
        intent = new Intent(this, MusicService.class);
        animation = AnimationUtils.loadAnimation(this, R.anim.tip);
        LinearInterpolator lin = new LinearInterpolator();
        animation.setInterpolator(lin);
        if (animation != null) {
            backgroundMusic.startAnimation(animation);
            startService(intent);
            //开始播放音乐
        }
    }

    private void viewpagerChangeListener() {
        horizontalViewPager.addOnPageChangeListener(new AutoNotifyViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.e(TAG, "horizontal-onPageScrolled: position=" + position + "---positionOffset=" + positionOffset + "positionOffsetPixels=" + positionOffsetPixels);
                if (position == 0) {
                    getAnimation(holder.myWebView);//第一页执行动画
                }
                View horizontalView = horizontalViewPager.findViewWithTag(horizontalViewPager.getCurrentItem());
                VerticalViewPager pa = (VerticalViewPager) horizontalView.findViewById(R.id.vertical_viewpager);
//                //首页不加载方式
                Log.e(TAG, "VerticalViewPager: " + pa + "horizontalViewPager.getCurrentItem()=" + horizontalViewPager.getCurrentItem() + "position=" + position);

                if (pa != null) {
                    View verticalView = pa.findViewWithTag(pa.getCurrentItem());
                    MyWebView myWebView = (MyWebView) verticalView.findViewById(R.id.my_web);

                    if (positionOffsetPixels >0&&isAnimation) {
                        //向右侧滑动
                        Log.e(TAG, "horizontalViewPager-onPageSelected: position==" + position + "positionOffsetPixels==" + positionOffsetPixels);
                        Log.e(TAG, "horizontal--onPageSelected: =============" + listMap.get(position).get(pa.getCurrentItem()));
                        myWebView.loadUrl("javascript:slideOutView()");//执行结束动画
//                        isAnimation  =false;
                    } else if (positionOffset == 0.0 && positionOffsetPixels == 0&&position == horizontalViewPager.getCurrentItem()) {
                        myWebView.loadUrl("javascript:slideIntoView()");
                        Log.e(TAG, "horizontalViewPager-onPageSelected: position==" + position);
                        Log.e(TAG, "horizontal--onPageSelected: =============" + listMap.get(position).get(pa.getCurrentItem()));

//                        isAnimation = false;
                    }
                }
                Log.e(TAG, "onPageSelected: 3");
            }

            @Override
            public void onPageSelected(int position) {
                horizontalPageText.setText((position + 1) + "");
                vTotalPageText.setText("共" + listMap.get(position).size() + "页");
//                currentPage.setText((position + 1) + "");
                totalPage.setText(listMap.get(position).size() + "");
                Log.e(TAG, "onPageSelected: 1" + position);
            }

            //            状态改变的时候调用
            @Override
            public void onPageScrollStateChanged(int state) {
                Log.e(TAG, "onPageSelected: 2" + "state=" + state);
            }
        });
    }

    private String initData() {
        layoutInflater = getLayoutInflater();
        //接收
        Intent intent = getIntent();
        uid = intent.getStringExtra("uid");
        projectId = intent.getStringExtra("projectId");
//        isOnLine = intent.getStringExtra("isOnLine");
        pageType = intent.getStringExtra("pageType");
        boolean isOnline = intent.getBooleanExtra("isOnline", false);
        Log.e(TAG, "initData: " + projectId + "---" + uid + "---" + isOnLine + "---" + pageType);
        sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator
                + GlobalVars.getPackageInfo().packageName
                + "/download"
                + File.separator + uid + "/" + projectId + "/" + projectId + ".json";
        String readFile = FileUtil.readFile(sdcardRoot);//读取本地json文件
        try {
            JSONObject jsonObject = new JSONObject(readFile);
            JSONObject jsonObject2 = jsonObject.getJSONObject("project");
            JSONArray publish = jsonObject2.getJSONArray("publish");
            for (int i = 0; i < publish.length(); i++) {
                JSONObject jsonObject3 = publish.getJSONObject(i);
                int index = jsonObject3.getInt("index");
                JSONArray pages = jsonObject3.getJSONArray("pages");
                List<String> webUrlPath = new ArrayList<>();
                for (int j = 0; j < pages.length(); j++) {
                    String sdcardRoot1 = Environment.getExternalStorageDirectory().getAbsolutePath()
                            + File.separator
                            + GlobalVars.getPackageInfo().packageName
                            + "/download"
                            + File.separator + uid + "/";
                    JSONObject jsonObject4 = pages.getJSONObject(j);
                    String pageId = jsonObject4.getString("id");
                    Log.e("PAGEID", "initData: " + pageId);
                    if (pageType.equals("phone")) {
                        weburl = "file://" + sdcardRoot1 + "web/preview/index.html?projectId=" + projectId +
                                "&pageId=" + pageId + "&pageType=phone" + "&isClient=true";
                    } else if (pageType.equals("pad")) {
                        weburl = "file://" + sdcardRoot1 + "web/preview/index.html?projectId=" + projectId +
                                "&pageId=" + pageId + "&pageType=pad" + "&isClient=true";
                    } else if (pageType.equals("phone") && isOnline == true) {
                        weburl = "http://" + sdcardRoot1 + "web/preview/index.html?projectId=" + projectId +
                                "&pageId=" + pageId + "&pageType=phone" + "&review=true";
                    } else if (pageType.equals("pad") && isOnline == false) {
                        weburl = "http://" + sdcardRoot1 + "web/preview/index.html?projectId=" + projectId +
                                "&pageId=" + pageId + "&pageType=pad" + "&review=true";
                    }
                    Log.e("WEBURL", "initData: " + weburl);
                    webUrlPath.add(weburl);
                }
                listMap.put(index, webUrlPath);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return pageType;
    }

    private void initView() {
        horizontalViewPager = (AutoNotifyViewPager) findViewById(R.id.content_horizontal_viewpager);
        frameLayout = (DragFrameLayout) findViewById(R.id.becausefloat);

        fab = (RelativeLayout) findViewById(R.id.show_hide_fab);

        bottomSelector = (RelativeLayout) findViewById(R.id.bottom_selector);
        veritcalPageText = (TextView) findViewById(R.id.vertical_text);
        vTotalPageText = (TextView) findViewById(R.id.vertical_total_text);
        horizontalPageText = (TextView) findViewById(R.id.horizontal_text);
        hTotalPageText = (TextView) findViewById(R.id.horizontal_total_text);
        backgroundMusic = (ImageView) findViewById(R.id.background_music);
        currentPage = (TextView) findViewById(R.id.currentPage);
        totalPage = (TextView) findViewById(R.id.totalPage);
        stopImg = (ImageView) findViewById(R.id.stop_down_img);
//        frameLayout.setDragImageListener(new DragFrameLayout.DragImageClickListener() {
//            @Override
//            public void onClick() {
//                if (mPopupWindow != null && mPopupWindow.isShowing()) {
//                    fab.setVisibility(View.VISIBLE);
//                    mPopupWindow.dismiss();
//                    return;
//                } else {
//                    initPop();
//                    int[] location = new int[2];
//                    view.getLocationInWindow(location);
//                    mPopupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//                    fab.setVisibility(View.GONE);//弹出popupWindow同时设置悬浮按钮为不可见
//                }
//            }
//        });
    }

    //初始化popupwindow
    private void initPop() {
        view = LayoutInflater.from(this).inflate(R.layout.pop_test, null);
        recyclerView = (RecyclerView) view.findViewById(R.id.scroll_first);
        layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(layoutManager);
        mPopupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setFocusable(true);//可点击
        // 点击其他地方消失
//        view.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (mPopupWindow != null && mPopupWindow.isShowing()) {
//                    mPopupWindow.dismiss();
//                    mPopupWindow = null;
//                    fab.setVisibility(View.VISIBLE);
//                }
//                return false;
//            }
//        });

        //设置点击其他位置popupwindow消失
        mPopupWindow.setOutsideTouchable(true);
        //设置位置
        //设置pop显示与消失
        mPopupWindow.setAnimationStyle(R.style.BottomMenuAnim);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        //例化一个ColorDrawable颜色为半透明
        mPopupWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.popwindow_background));
//        mPopupWindow.showAtLocation(, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);
        CheckBox textView = (CheckBox) view.findViewById(R.id.switch_off_on);
        image1 = (RecyclerView) view.findViewById(R.id.scroll_first);
        image2 = (RecyclerView) view.findViewById(R.id.scroll_second);
        image1.setVisibility(View.VISIBLE);
        image2.setVisibility(View.GONE);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (image1.getVisibility() == View.VISIBLE) {
                    image1.setVisibility(View.GONE);
                    image2.setVisibility(View.VISIBLE);
                } else {
                    image1.setVisibility(View.VISIBLE);
                    image2.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.background_music:
                if (!isPlay) {
//                    stopService(intent);//
//                    binder.pause();
                    startService(intent);
                    backgroundMusic.clearAnimation();
                    backgroundMusic.setImageResource(R.mipmap.music_stop);
//                    isPlay = false;
                } else {
                    if (animation != null) {
                        backgroundMusic.startAnimation(animation);
                        backgroundMusic.setImageResource(R.mipmap.music_play);
                    }
//                    isPlay = true;
                    startService(intent);
//                    bindService(intent,connection,BIND_AUTO_CREATE);//绑定服务
                }
                isPlay = !isPlay;
                break;
            case R.id.stop_down_img:
                Intent intent = new Intent(ContentActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

    //垂直的adapter
    public class MyVerticalPagerAdapter extends android.support.v4.view.PagerAdapter {
        private int mPosition;
        private Context context;
        private List<MyWebView> webList;

        public MyVerticalPagerAdapter(int position, Context context) {
            mPosition = position;
            this.context = context;
//            webList = new ArrayList<>();
//            for (int i=0;i<list.size();i++){
//                MyWebView webView=new MyWebView(getApplicationContext());
//                webView.loadUrl(list.get(i));
//                webList.add(webView);
//            }
        }

        @Override
        public int getCount() {
            return listMap.get(mPosition).size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            list = listMap.get(mPosition);//通过键position获取到map中的值value
            //复用
            View convertView = null;
            if (mViewCache.size() == 0) {
                convertView = LayoutInflater.from(context).inflate(R.layout.webview_layout, null);
                holder = new ViewHolder();
                holder.myWebView = (MyWebView) convertView.findViewById(R.id.my_web);
//                if (Build.VERSION.SDK_INT >= 19) {
//                    holder.myWebView.getSettings().setLoadsImagesAutomatically(true);
//                } else {
//                    holder.myWebView.getSettings().setLoadsImagesAutomatically(false);
//                }
//                //暂时关闭硬件加速
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//                    holder.myWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//                }
//                //不加上，会显示白边
//                holder.myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//                holder.myWebView.setInitialScale(39);//适应全屏
                convertView.setTag(holder);
                Log.e("TAG", "first---instantiateItem: ");
            } else {
                convertView = mViewCache.removeFirst();
                holder = (ViewHolder) convertView.getTag();
                Log.e("TAG", "second----instantiateItem: ");
            }
//            Log.e("TAGTAG", "instantiateItem: " + list.get(position));
            getWebSetting(holder.myWebView);

            IX5WebViewExtension x5WebViewExtension = holder.myWebView.getX5WebViewExtension();
            Log.e(TAG, "IX5WebViewExtension:---- " + x5WebViewExtension);
            holder.myWebView.loadUrl(list.get(position));
            holder.myWebView.setTag(position);
            container.addView(convertView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            if (position == 0) {
//                holder.myWebView.loadUrl("javascript:slideIntoView()");
                getAnimation(holder.myWebView);
            }
            return convertView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    public void getWebSetting(MyWebView myWebView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            myWebView.setWebContentsDebuggingEnabled(true);
        }
        webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
//        加载需要显示的网页
        webSettings.setBlockNetworkImage(false);
        webSettings.setBlockNetworkLoads(false);
        //开启DOM storage API功能
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);  //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//      webSettings.setAppCacheEnabled(true);//设置H5的缓存是否开启
//      webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
//      webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //根据cache-control决定是否从网络上取数据。
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//不使用网络，只读取本地缓存数据
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        //webview   解决遇到的跨域问题
        webSettings.setAllowFileAccessFromFileURLs(true);
    }

    private void getAnimation(MyWebView myWebView) {

        myWebView.setWebViewClient(new WebViewClient() {
                                       @Override
                                       public boolean shouldOverrideUrlLoading(com.tencent.smtt.sdk.WebView webView, String s) {
                                           return true;
                                       }

                                       @Override
                                       public com.tencent.smtt.export.external.interfaces.WebResourceResponse shouldInterceptRequest(com.tencent.smtt.sdk.WebView webView, String s) {
                                           return parseUrl(s);
                                       }


                                       //                                       @Override
//                                       public com.tencent.smtt.export.external.interfaces.WebResourceResponse shouldInterceptRequest(com.tencent.smtt.sdk.WebView view, String url) {
//                                           return parseUrl(url);
//                                       }
//
//                                       @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                                       @Override
                                       public com.tencent.smtt.export.external.interfaces.WebResourceResponse shouldInterceptRequest(com.tencent.smtt.sdk.WebView webView, com.tencent.smtt.export.external.interfaces.WebResourceRequest webResourceRequest) {
                                           return parseUrl(webResourceRequest.getUrl().getPath());
                                       }

                                       @Override
                                       public void onPageStarted(com.tencent.smtt.sdk.WebView webView, String s, Bitmap bitmap) {
                                           super.onPageStarted(webView, s, bitmap);
                                       }

                                       @Override
                                       public void onPageFinished(com.tencent.smtt.sdk.WebView webView, String s) {
                                           super.onPageFinished(webView, s);
                                           Log.e(TAG, "onPageFinished: ------true----" + s);
                                           webView.loadUrl("javascript:slideIntoView()");
                                       }
                                   }
        );
    }

    public class ViewHolder {
        private MyWebView myWebView;
    }

    //展示水平的数据
    public class MyHorizontalPagerAdapter extends android.support.v4.view.PagerAdapter {
        @Override
        public int getCount() {
            return listMap.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(final ViewGroup container, final int position) {
            //-----------------------------------------
            ViewGroup parent = (ViewGroup) verticalList.get(position).getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
            verticalList.get(position).setTag(position);
            container.addView(verticalList.get(position));
            return verticalList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(intent);
    }

    //获取图片路径
    public com.tencent.smtt.export.external.interfaces.WebResourceResponse parseUrl(String url) {
        String uid = ResourceFileManager.splitUrl(url, 3);
        Log.i(TAG, "shouldInterceptRequest url=" + url + ";threadInfo" + Thread.currentThread());
        Log.e(TAG, "parseUrl:------------" + url);
        String mainPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator
                + GlobalVars.getPackageInfo().packageName
                + "/download"
                + File.separator;
        if (url.contains("public_resource/files/image")) {
            String img = ResourceFileManager.splitImgUrlPath(url).substring(
                    ResourceFileManager.splitImgUrlPath(url).lastIndexOf("/") + 1);
            Log.e(TAG, "parseUrl: --------img----" + img);

            String path = mainPath + "public_resource/files/image/" + img;
            InputStream in = null;
            try {

                in = new FileInputStream(path);
                Log.e(TAG, "FileInoutStreamParseUrl: --------" + path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.e(TAG, "parseUrl: 文件没找到！");
            }
            return new com.tencent.smtt.export.external.interfaces.WebResourceResponse("text/html", "utf-8", in);
        } else if (url.contains(uid + "/files/image")) {
            String imgUrlPath = ResourceFileManager.splitImgUrlPath1(url);
            String substring = imgUrlPath.substring(imgUrlPath.lastIndexOf("/") + 1);
            String dir1 = ResourceFileManager.splitUrl(url, 4);//uid
            //方案
            String dir2 = ResourceFileManager.splitUrl(url, 5);
            String path = mainPath + uid + "/" + dir1 + "/" + dir2 + "/" + substring;
            Log.e(TAG, "imgUrlPath: " + path);
            InputStream in = null;
            try {
                in = new FileInputStream(path);
                Log.e(TAG, "FileInoutStreamParseUrl: --------" + path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.e(TAG, "parseUrl: 文件没找到！");
            }
            return new com.tencent.smtt.export.external.interfaces.WebResourceResponse("text/html", "utf-8", in);
        }
        return null;
    }
}
